from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import json


def 获取cookie(url):
    # 打开浏览器
    driver = webdriver.Edge(service=Service())

    try:
        # 进入网页
        driver.get(url)
        print("请手动登录...")

        # 等待用户手动登录，或设置一个显式等待时间等待特定元素的出现
        WebDriverWait(driver, 120).until(EC.presence_of_element_located((By.CLASS_NAME, "label-text")))

        # 登录成功后，获取所有cookie信息(返回是字典)
        dictCookies = driver.get_cookies()

        # 将dict转化成str格式
        jsonCookies = json.dumps(dictCookies)

        # 6. 创建一个json文件，将cookies保存到该路径
        cookie_path = '../boss直聘Edge.json'
        with open(cookie_path, "w", encoding="utf-8") as fp:
            fp.write(jsonCookies)
            print('cookies保存成功！')

    finally:
        # 关闭浏览器
        driver.quit()


url = 'https://www.zhipin.com/web/geek/job-recommend'

if __name__ == '__main__':
    获取cookie(url)
